# Flask框架导入
from flask import render_template, redirect, url_for, request, flash, abort, current_app
from sqlalchemy.exc import SQLAlchemyError
import logging

# 蓝图和装饰器导入
from . import approval_bp
from ..utils import member_login_required, get_current_member


# 服务层函数导入
from .services import (
    get_approvals,
    submit_approval,
    review_approval,
    get_review_list,
    get_pending_approval_count,
    get_approval_history
)

# 模型导入
from inc.models import JiraReview, db, JiraApprovalStep, JiraProject

# 设置日志
logger = logging.getLogger(__name__)

@approval_bp.context_processor
def inject_current_member():
    """在所有模板中注入当前用户"""
    return dict(current_member=get_current_member())


@approval_bp.route('/')
@member_login_required
def list_approvals():
    """我的审批列表"""
    current_member = get_current_member()
    approvals = get_approvals(current_member.id)
    pending_count = get_pending_approval_count(current_member.id)
    return render_template(
        'member/approval/list.html',
        approvals=approvals,
        pending_count=pending_count
    )

@approval_bp.route('/review')
@member_login_required
def review_list():
    """待我审批的列表"""
    current_member = get_current_member()
    try:
        approvals = get_review_list(current_member.id)
        pending_count = get_pending_approval_count(current_member.id)
        return render_template(
            'member/approval/review_list.html',
            approvals=approvals,
            pending_count=pending_count
        )
    except Exception as e:
        current_app.logger.error(f"获取审批列表失败: {str(e)}", exc_info=True)
        flash('获取审批列表失败', 'danger')
        return redirect(url_for('member.dashboard'))

@approval_bp.route('/<int:approval_id>/detail')
@member_login_required
def review_detail(approval_id):
    """审批详情"""
    current_member = get_current_member()
    try:
        approval = JiraReview.query.options(
            db.joinedload(JiraReview.project),
            db.joinedload(JiraReview.submitter),
            db.joinedload(JiraReview.reviewer)
        ).get_or_404(approval_id)

        # 统一权限检查逻辑
        if (approval.reviewer_id != current_member.id and
            approval.submitter_id != current_member.id and
            not current_member.has_permission('REVIEW_PROJECT')):
            abort(403)

        # 获取审批历史记录
        history = get_approval_history(approval.project_id)

        # 处理审批步骤，不再在此处进行数据库写操作
        current_step = None
        next_steps = []
        all_steps = []

        if approval.project_id and approval.project.approval_flow:
            # 获取所有审批步骤并按顺序排序
            all_steps = JiraApprovalStep.query.filter_by(
                flow_id=approval.project.approval_flow_id
            ).order_by(JiraApprovalStep.order).all()

            # 如果 approval.step_id 不为 None，获取当前步骤
            if approval.step_id:
                current_step = next((step for step in all_steps if step.id == approval.step_id), None)
            elif all_steps:
                # 如果 step_id 为 None，仅为了显示目的，将第一个步骤视为当前步骤
                current_step = all_steps[0]

            # 获取后续步骤
            if current_step:
                next_steps = [
                    step for step in all_steps
                    if step.order > current_step.order
                ]

        pending_count = get_pending_approval_count(current_member.id)
        return render_template(
            'member/approval/review_detail.html',
            approval=approval,
            history=history,
            current_step=current_step,
            next_steps=next_steps,
            all_steps=all_steps,
            pending_count=pending_count
        )

    except Exception as e:
        current_app.logger.error(f"查看审批详情时出错: {str(e)}", exc_info=True)
        abort(500, description="无法加载审批详情")


@approval_bp.route('/<int:approval_id>/review', methods=['POST'])
@member_login_required
def review(approval_id):
    """审批处理"""
    current_member = get_current_member()

    try:
        action = request.form.get('action')
        notes = request.form.get('notes', '')

        if not action or action not in ('approve', 'reject'):
            flash('无效的操作', 'danger')
            return redirect(url_for('member.approval.review_detail', approval_id=approval_id))

        # 常规审批处理
        approval = review_approval(approval_id, current_member.id, action, notes)
        project = JiraProject.query.get(approval.project_id) if approval.project_id else None

        # 设置成功消息
        if action == 'approve':
            if project and project.status == 'approved':
                flash('审批已通过，项目已完成所有审批流程', 'success')
            else:
                flash('审批已通过，等待后续审批', 'success')
        else:
            flash('审批已拒绝', 'success')

    except (ValueError, PermissionError) as e:
        flash(str(e), 'danger')
        return redirect(url_for('member.approval.review_detail', approval_id=approval_id))
    except Exception as e:
        current_app.logger.error(f"审批处理失败: {str(e)}", exc_info=True)
        flash(f'审批处理失败: {str(e)}', 'danger')
        return redirect(url_for('member.approval.review_detail', approval_id=approval_id))

    # 重定向逻辑
    if project and project.status == 'approved':
        return redirect(url_for('member.jira.project_detail', project_id=project.id))
    else:
        return redirect(url_for('member.approval.review_detail', approval_id=approval_id))